#include "wifiservice.h"

extern rt_uint32_t dhtemp;
extern rt_uint32_t dhhumi;

//int switchstatus = 1;

#define SAMPLE_UART_NAME "uart2"

/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;

static rt_thread_t wifiservice_thread = RT_NULL;


/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

void uartsend(char dat)
{
    // rt_kprintf("write dat:0x%02x\n",dat);
    rt_device_write(serial, 0, &dat, 1);
}

void wifi_service_thread(void *param)
{
    rt_kprintf("wifiservice_thread start.\n");
    char str[] = "hello RT-Thread!\r\n";
    char ch;
    serial = rt_device_find(SAMPLE_UART_NAME);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", SAMPLE_UART_NAME);
        // return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
    /* 发送字符串 */
    rt_device_write(serial, 0, str, (sizeof(str) - 1));

    wifi_protocol_init();

    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
            //rt_thread_mdelay(200);
        }

        // rt_kprintf("ch:0x%02x\n",ch);
        uart_receive_input(ch);

        wifi_uart_service();
    }
}
static int timer_count = 0;
void wifitimer_out(void *parameter)
{
    timer_count++;
    mcu_get_wifi_connect_status();
    if (timer_count % 5 == 0)
    {
        mcu_get_system_time();
        //rt_kprintf("wifi report switch:%d\n", switchstatus);
       // mcu_dp_bool_update(DPID_SWITCH_1, switchstatus); // BOOL型数据上报;
        rt_kprintf("wifi report temp:%d\n", dhtemp);
        mcu_dp_value_update(DPID_TEMP_CURRENT, dhtemp); // VALUE型数据上报;
        int humi = (int)((float)dhhumi / 10 + 0.5);
        rt_kprintf("wifi report humi:%d\n", humi);
        mcu_dp_value_update(DPID_HUMIDITY, humi); // VALUE型数据上报;
        timer_count = 0;
    }
}
int wifiservice_init()
{
    wifiservice_thread = rt_thread_create("uart2wifi", wifi_service_thread, RT_NULL, 2048, 15, 20);
    if (wifiservice_thread != RT_NULL)
    {
        rt_thread_startup(wifiservice_thread);
    }
    else
    {
        rt_kprintf("wifiservice_thread create failed.\n");
        return RT_ERROR;
    }

    rt_timer_t wifitimer = rt_timer_create("wifitimer", wifitimer_out,
                                           RT_NULL, 1000,
                                           RT_TIMER_FLAG_PERIODIC);

    /* 启动定时器 2 */
    if (wifitimer != RT_NULL)
    {
        rt_timer_start(wifitimer);
    }
    else
    {
        rt_kprintf("wifitimer create failed.\n");
        return RT_ERROR;
    }
}
